package etc.task;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.extra.ftp.Ftp;
import com.dmz.test.etc.config.EnvConfig;
import com.dmz.test.etc.config.enums.MsgType;
import com.dmz.test.etc.config.enums.TaskStatus;
import com.dmz.test.etc.domain.ClientTask;
import com.dmz.test.etc.netty.client.NettyClient;
import com.dmz.test.etc.utils.FileUtil;
import com.dmz.test.etc.utils.etc.DateTools;
import com.dmz.test.etc.utils.ftp.FtpClient;
import com.dmz.test.etc.utils.ftp.FtpFile;
import com.dmz.test.etc.utils.ftp.FtpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/**
 * @author Laptop
 */
@Slf4j
@Component
public class TaskService {

    public void task2051() {
        try {
            ClientTask task = initTasks("2051");
            if (checkTasks(task)) {
                executeDayTask(task);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void task4031() {

        try {
            ClientTask task = initTasks("4031");
            if (checkTasks(task)) {
                executeDayTask(task);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void task4051() {
        try {
            ClientTask task = initTasks("4051");
            if (checkTasks(task)) {
                executeDayTask(task);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private ClientTask initTasks(String type) {
        Ftp ftp = new FtpClient().bankFtp();
        //2051  充值对账文件发送通知报文

        String endStr = EnvConfig.getProperty("dmz.ftp.file.fileName.end");
        String remotePath = EnvConfig.getProperty("dmz.ftp.file.path.bank");
        String localPath = EnvConfig.getProperty("dmz.ftp.file.path.temp");
        ClientTask clientTask = new ClientTask();
        if ("2051".equals(type)) {
            String fileName2051 = EnvConfig.getProperty("dmz.ftp.file.fileName.cz2051").replace("{yesterday}", DateTools.getYesterday()).replace("{today}", DateTools.getDateStr());
            FtpFile file2051 = new FtpFile(ftp, remotePath, localPath, fileName2051, endStr);
            log.info(file2051.toString());

            clientTask.setFtpFile(file2051);
            clientTask.setTaskStatus(TaskStatus.STATUS_CREATED);
            clientTask.setMsgType(MsgType.TYPE_2051);
        }

        if ("4031".equals(type)) {
            String fileName4031 = EnvConfig.getProperty("dmz.ftp.file.fileName.bc4031").replace("{yesterday}", DateTools.getYesterday()).replace("{today}", DateTools.getDateStr());
            FtpFile file4031 = new FtpFile(ftp, remotePath, localPath, fileName4031, endStr);
            log.info(file4031.toString());

            clientTask.setFtpFile(file4031);
            clientTask.setTaskStatus(TaskStatus.STATUS_CREATED);
            clientTask.setMsgType(MsgType.TYPE_4031);
        }

        if ("4051".equals(type)) {
            String fileName4051 = EnvConfig.getProperty("dmz.ftp.file.fileName.kj4051").replace("{yesterday}", DateTools.getYesterday()).replace("{today}", DateTools.getDateStr());
            FtpFile file4051 = new FtpFile(ftp, remotePath, localPath, fileName4051, endStr);
            log.info(file4051.toString());

            clientTask.setFtpFile(file4051);
            clientTask.setTaskStatus(TaskStatus.STATUS_CREATED);
            clientTask.setMsgType(MsgType.TYPE_4051);

        }
        return clientTask;
    }

    private boolean checkTasks(ClientTask task) {
        return !(task.getTaskStatus() == TaskStatus.STATUS_COMPLETE);
    }

    private void executeDayTask(ClientTask t) throws IOException {
        switch (t.getTaskStatus()) {
            case STATUS_CREATED:
                if (downloadFile(t.getFtpFile())) {
                    t.setTaskStatus(TaskStatus.STATUS_FILE_DOWNLOADED);
                    asyncExecuteTask(t);
                }
                break;
            case STATUS_FILE_DOWNLOADED:
                asyncExecuteTask(t);
                break;
            default:
                break;
        }
    }

    private void asyncExecuteTask(ClientTask t) {
        CompletableFuture<TaskStatus> future = CompletableFuture.supplyAsync(() -> {
            // 启动客户端发送报文
            try {
                if (FileUtil.localExist(t.getFtpFile())) {
                    t.setTaskStatus(TaskStatus.STATUS_SENDING);
                    new NettyClient().start(t);
                    return TaskStatus.STATUS_COMPLETE;
                } else {
                    return t.getTaskStatus();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return TaskStatus.STATUS_FILE_DOWNLOADED;
        });
        // 在这里处理异步操作的结果
        future.thenAccept(t::setTaskStatus);
    }

    private boolean downloadFile(FtpFile file) throws IOException {
        try {
            if (FtpUtil.remoteExist(file)) {
                FtpUtil.download(file);
                return true;
            }else {
                log.info("ftp上无文件");
            }
        } catch (IORuntimeException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new IOException(e);
        }
        return false;
    }
}